package com.suke.czx.modules.bus.controller;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.web.bind.annotation.*;
import com.suke.czx.modules.bus.entity.BusCharterInfo;
import com.suke.czx.modules.bus.service.BusCharterInfoService;
import com.suke.zhjg.common.autofull.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import java.util.TimeZone;


/**
 * 包车标志牌信息表
 *
 * @author chenshuang
 * @email 1299492720@qq.com
 * @date 2025-09-01 11:01:41
 */
@RestController
@AllArgsConstructor
@RequestMapping("/bus/busCharterInfo")
@Api(value = "BusCharterInfoController", tags = "包车标志牌信息表")
public class BusCharterInfoController extends AbstractController {
    private final BusCharterInfoService busCharterInfoService;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // GitHub Pages配置（用户需替换为自己的仓库信息）
    private static final String GITHUB_PAGES_URL = "https://chenshuanggithub.github.io/cs.github.io/index.html";

    static {
        DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 确保时区与@JsonFormat一致
    }
    @ApiOperation(value = "生成包车信息二维码")
    @PostMapping("/generateQrCode")
    public R generateQrCode(@RequestBody BusCharterInfo busCharterInfo) {
        try {
            String charterLink = generateGitHubPagesLink(busCharterInfo);
            HashMap<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);

            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(charterLink, BarcodeFormat.QR_CODE, 400, 400, hints);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());

            return R.ok()
                    .put("qrCode", "data:image/png;base64," + base64Image)
                    .put("charterLink", charterLink);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("生成二维码失败: " + e.getMessage());
        }
    }

    private String generateGitHubPagesLink(BusCharterInfo charterInfo) throws Exception {
        StringBuilder params = new StringBuilder();

        // 车辆基本信息
        params.append("?vehicleNumber=").append(URLEncoder.encode(getValue(charterInfo.getVehicleNumber()), StandardCharsets.UTF_8.name()));
//        params.append("&vehicleColor=").append(URLEncoder.encode(getValue(charterInfo.getVehicleColor()), StandardCharsets.UTF_8.name()));

        // 驾驶员与企业信息
        params.append("&driverName=").append(URLEncoder.encode(getValue(charterInfo.getDriverName()), StandardCharsets.UTF_8.name()));
        params.append("&transportCompany=").append(URLEncoder.encode(getValue(charterInfo.getTransportCompany()), StandardCharsets.UTF_8.name()));
        params.append("&signSerialNumber=").append(URLEncoder.encode(getValue(charterInfo.getSignSerialNumber()), StandardCharsets.UTF_8.name()));
        params.append("&reserved1=").append(URLEncoder.encode(getValue(charterInfo.getReserved1()), StandardCharsets.UTF_8.name()));

        // 行程路线信息
        params.append("&startLocation=").append(URLEncoder.encode(getValue(charterInfo.getStartLocation()), StandardCharsets.UTF_8.name()));
        params.append("&endLocation=").append(URLEncoder.encode(getValue(charterInfo.getEndLocation()), StandardCharsets.UTF_8.name()));
        params.append("&viaLocation=").append(URLEncoder.encode(getValue(charterInfo.getViaLocation()), StandardCharsets.UTF_8.name()));

        // 有效期信息（按@JsonFormat指定格式格式化）
        params.append("&validStart=").append(URLEncoder.encode(formatDate(charterInfo.getValidStart()), StandardCharsets.UTF_8.name()));
        params.append("&validEnd=").append(URLEncoder.encode(formatDate(charterInfo.getValidEnd()), StandardCharsets.UTF_8.name()));

        return GITHUB_PAGES_URL + params.toString();
    }


    /**
     * 列表
     */
    @ApiOperation(value = "包车标志牌信息表列表")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        QueryWrapper<BusCharterInfo> queryWrapper = new QueryWrapper<>();
        final String keyword = mpPageConvert.getKeyword(params);
        if (StrUtil.isNotEmpty(keyword)) {

        }
        IPage<BusCharterInfo> listPage = busCharterInfoService.page(mpPageConvert.<BusCharterInfo>pageParamConvert(params), queryWrapper);
        return R.ok().setData(listPage);
    }

    /**
     * 处理null值，避免空指针异常
     */
    private String getValue(String value) {
        return value != null ? value : "";
    }

    /**
     * 格式化日期为指定格式，处理null值
     */
    private String formatDate(Date date) {
        if (date == null) {
            return "";
        }
        return DATE_FORMAT.format(date);
    }

    /**
     * 新增包车标志牌信息表
     */
    @ApiOperation(value = "新增包车标志牌信息表数据")
    @SysLog("新增包车标志牌信息表数据")
                @PostMapping("/save")
            public R save(@RequestBody BusCharterInfo busCharterInfo) {
            busCharterInfoService.save(busCharterInfo);
        return R.ok();
    }


    /**
     * 修改
     */
    @ApiOperation(value = "修改包车标志牌信息表数据")
    @SysLog("修改包车标志牌信息表数据")
                @PostMapping("/update")
            public R update(@RequestBody BusCharterInfo busCharterInfo) {
            busCharterInfoService.updateById(busCharterInfo);
        return R.ok();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除包车标志牌信息表数据")
    @SysLog("删除包车标志牌信息表数据")
                @PostMapping("/delete")
            public R delete(@RequestBody BusCharterInfo busCharterInfo) {
            busCharterInfoService.removeById(busCharterInfo.getId());
        return R.ok();
    }

}
